<template>
    <div>
        <el-card class="box-card" style="width: 98%;margin-left: 1%">
            <el-tabs v-model="activeName" @tab-click="handleClick">
                <el-tab-pane v-for="(item,index) in categoryTypes" :label="item.name" :name="item.code+''"></el-tab-pane>
            </el-tabs>

            <el-row>
                <!-- 左边媒体分类树结构数据 -->
                <el-col :span="5">
                    <el-card class="box-card" style="width: 98%; height: 600px;overflow: auto ">
                        <avue-tree ref="tree"
                                   :option="treeOption"
                                   :data="treeData"
                                   @node-click="nodeClick">
                                  <span class="el-tree-node__label" slot-scope="{ node, data }">
                                  <span>
                                    <i v-if="data.showType==1" class="el-icon-folder-opened"></i>
                                    <i v-if="data.showType==2" class="el-icon-document"></i>
                                    {{ data.name }}
                                  </span>
                                </span>
                            <template slot-scope="scope" slot="menu">
                                <!--  <div class="avue-tree__item" @click="updRow(scope.node,0)"><i class="el-icon-plus"> 顶级目录/文档</i></div>-->
                                <div class="avue-tree__item" @click="updRow(scope.node.data,2)" v-show="scope.node.data.showType == 1"><i class="el-icon-plus"> 子级目录/文档</i></div>
                                <div class="avue-tree__item" @click="updRow(scope.node.data,4)"><i class="el-icon-edit"> 变更父级</i></div>
                                <div class="avue-tree__item" @click="updRow(scope.node.data,1)"><i class="el-icon-edit"> 编辑</i></div>
                                <div class="avue-tree__item" @click="updRow(scope.node.data,5)"><i class="el-icon-delete"> 删除</i></div>
                                <div class="avue-tree__item" @click="findLeftTree()"><i class="el-icon-refresh"> 刷新</i></div>

                            </template>
                        </avue-tree>
                    </el-card>
                </el-col>
                <el-col id="docList" :span="19">
                    <avue-crud style="width: 98%; margin-left: 1%" ref="crudMenu"
                               :data="data"
                               :option="option"
                               :page.sync="page"
                               :search.sync="search"
                               :table-loading="loading"
                               :cell-style="cellStyle"
                               @sort-change="sortChange"
                               @refresh-change="onLoad"
                               @search-change="searchChange"
                               @row-click="handleRowClick">

                        <template slot-scope="" slot="menuLeft">
                            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="updRow(rowData,0)">顶级</el-button>
                            <!--                            <el-button type="primary" plain icon="el-icon-plus" v-show="rowData.showType == 1" size="mini" @click="updRow(rowData,2)">子级文档</el-button>-->
                            <!--  <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="updRow(rowData,4)">变更父级</el-button>-->
                            |
                            <el-button type="primary" plain size="mini" @click="delDocAllByType">删除文档</el-button>
                            <el-button type="primary" plain size="mini" @click="importMdDialogVisible = true">导入文档</el-button>
                            <el-button type="primary" plain size="mini" @click="refreshHtml()">更新文档 HTML</el-button>
                            |
                            <el-button type="primary" plain size="mini" @click=" exportMd()">导出文档</el-button>
                            <el-button type="primary" plain size="mini" @click=" exportMdDownload()">导出下载</el-button>
                            |
                            <el-button type="primary" plain size="mini" @click=" staticMd()">静态化文档</el-button>
                            <el-button type="primary" plain size="mini" @click=" staticMdDownload()">静态化下载</el-button>
                            |
                            <el-button type="primary" plain size="mini" @click="siteMap()">生成站点地图</el-button>
                        </template>
                        <!-- 列表上进行编辑sort -->
                        <template slot-scope="{row,index,type,size}" slot="sort">
                            <el-input v-model="row.sort" @blur="rowSortBlur(row)" placeholder=""></el-input>
                        </template>
                        <template slot-scope="{scope,row,index,type,size}" slot="disable">
                            <el-switch v-model="row.disable" @change="updDisable(row,index,row.disable)"
                                       active-color="#13ce66" inactive-color="#ff4949"
                                       :active-value=0 :inactive-value=1
                                       active-text="" inactive-text="">
                            </el-switch>
                        </template>
                        <template slot-scope="{row,index,type,size}" slot="menu">
                            <el-button icon="el-icon-edit" :size="size" :type="type" @click="updRow(row,1)">编辑</el-button>
                            <el-button icon="el-icon-edit" :size="size" :type="type" @click="updRow(row,3)">复制添加</el-button>
                            <el-button icon="el-icon-delete" :size="size" :type="type" @click="rowDel(row,index)">删除</el-button>
                        </template>
                        <template slot-scope="{row,index,type,size}" slot="head">
                            <el-avatar :src="row.head"></el-avatar>
                        </template>
                    </avue-crud>
                </el-col>

                <el-col id="docContentHtml" :span="19" hidden>
                    <el-card class="box-card" style="width: 98%;margin-left: 1%">
                        <!-- 加载一个隐藏的空编辑器，取保展示内容的css文件被加载   -->
                        <MdEditor content.sync="" hidden/>
                        <span class="github-markdown-body" v-if="contentHtml!=null" v-html="contentHtml"></span>
                    </el-card>
                </el-col>
            </el-row>
        </el-card>
        <el-dialog title="变更父级" v-dialogDrag v-if="updPidDialogVisible" :visible.sync="updPidDialogVisible" width="25%" @close="closeDialog">
            <UpdPid :closeDialog="closeDialog" :uri="uri" :type="activeName" :rowData="rowData"></UpdPid>
            <span slot="footer" class="dialog-footer"></span>
        </el-dialog>
        <el-dialog title="导入文档" v-dialogDrag v-if="importMdDialogVisible" :visible.sync="importMdDialogVisible" width="35%" @close="closeDialog">
            <ImportMd :closeDialog="closeDialog" :uri="uri" :activeName="activeName" :categoryName="getCategoryType(activeName)"></ImportMd>
            <span slot="footer" class="dialog-footer"></span>
        </el-dialog>
    </div>
</template>


<script>

// import VueMarkdownEditor, {xss} from "@kangc/v-md-editor";
import VueMarkdownEditor, {xss} from '@kangc/v-md-editor/lib/codemirror-editor';

import {proxyPath} from "@/config/env";
import {getStore, setStore} from '@/util/store'

export default {

    components: {
        Add: () => import('./docInfoAdd'),
        Upd: () => import('./docInfoUpd'),
        UpdPid: () => import('./docInfoPid'),
        ImportMd: () => import('./importMd')
    },
    data() {
        return {
            uri: {
                infoList: "/api/admin/all/docInfo/tree",
                listIdNames: "/api/admin/all/docInfo/listIdNames",
                listCategory: "/api/admin/all/docCategory/list",
                info: "/api/admin/all/docInfo",
                updPidInfoList: "/api/admin/all/docInfo/tree?showType=1",
                updPid: "/api/admin/all/docInfo/updPid",
                updDisable: "/api/admin/all/docInfo/updDisable",
                updHtml: "/api/admin/all/docInfo/updHtml", //contentHtml
                updSort: "/api/admin/all/docInfo/updSort",
                delByType: "/api/admin/all/docInfo/delByType",
                exportMd: "/api/admin/all/export/export",
                getExportMdDownloadPath: "/api/admin/all/export/getExportMdDownloadPath",
                importMd: "/api/admin/all/export/import",
                generateSiteMap: "/api/admin/all/siteMap/generateSiteMap",
                staticMd: "/api/client/tp/gca",
                staticMdDownload: "/api/admin/all/siteMap/generateSiteMap",


            },
            loading: true,
            dialogWidth: "70%",
            addDialogVisible: false,      // 添加弹层开关状态
            updDialogVisible: false,      // 添加弹层开关状态
            updPidDialogVisible: false,      // 变更父级开关状态
            importMdDialogVisible: false,      // 导入弹层
            page: this.website.pageParams,   // 分页参数
            search: {    // 搜索参数
                sort: "sort",
                order: "asc",
            },
            treeOption: {
                filterText: "搜索关键字",       // 搜索提示
                defaultExpandAll: false,      // 是否展开节点
                filter: true,               // 是否显示搜索
                addBtn: false,              // 是否展示新增按钮
                editBtn: false,             // 是否展示删除按钮
                delBtn: false,              // 是否展示编辑按钮
                menu: true,                // 菜单开关
                defaultExpandedKeys: null,
                props: {
                    labelText: '标题',
                    label: 'name',
                    value: 'id',
                    children: 'children'
                }
            },
            treeData: [],
            data: [],                     // 右侧列表数据
            rowData: {},                  // 当前选中左侧菜单行数据/当前选中行数据
            contentHtml: null,            // 当前选中文档的 内容
            option: {},
            categoryTypes: {},    // 类型分类数据
            activeName: "",       // 当前选中类型(tab)

        }
    },
    mounted() {

        // 1、左侧菜单配置
        // this.treeOption = JSON.parse(JSON.stringify(this.website.treeOption))
        // this.treeOption.props.label = "name";
        // this.treeOption.props.children = "children";
        // this.treeOption.props.value = true;
        // this.treeOption.menu = true;

        this.init();
        // this.$nextTick(() => {
        //
        // })


        // 2、右侧表格配置 (树结构)
        this.option = JSON.parse(JSON.stringify(this.website.optionConfig));
        this.option.index = false;
        this.option.defaultExpandAll = true;
        // this.option.cellBtnt = true
        this.option.rowKey = "id";
        this.option.height = 600;
        this.option.searchBtnText = "搜索";
        // 字段配置
        this.option.treeProps = {
            children: 'children'
        };
        this.option.column =
            [
                {
                    label: '名称',
                    prop: 'name',
                    // width: 200,
                    search: false,
                    searchSpan: 5,
                    overHidden: true,
                },
                {
                    label: '作者',
                    prop: 'author',
                    // width: 200,
                    search: false,
                    searchSpan: 5,
                    overHidden: true,
                },
                {
                    label: '展示类型',
                    prop: 'showType',
                    type: 'radio',
                    dicData: this.dict.get('DOC_SHOW_TYPE', true),
                    span: 20,
                    rules: [{
                        required: true,
                        message: "请选择 是否禁用",
                        trigger: "blur"
                    }]
                },
                {
                    label: '排序',
                    prop: 'sort',
                    search: false,
                    searchSpan: 5,
                    overHidden: true,
                    sortable: "custom"
                },
                {
                    label: '禁用/启用',
                    prop: 'disable',
                    type: 'select',
                    search: false,
                    filterable: true,
                    searchSpan: 5,
                    overHidden: true,
                    dicData: this.dict.get('DISABLE'),
                    sortable: "custom"
                },
            ]
    },
    created() {
        //  console.log("created -  tenantName=" + this.$route.query.tenantName)

    },

    watch: {},

    methods: {
        init() {
            // 获取左侧数据默认选中id
            let id = this.$route.query.id
            // 默认展开
            this.treeOption.defaultExpandedKeys = id

            // 查询分类
            this.crud.get(this.uri.listCategory).then(res => {
                this.categoryTypes = res.data.data;
                // 设置当前分类
                let activeName = this.$route.query.activeName
                if (activeName != null) {
                    this.activeName = activeName + "";
                } else {
                    // 设置默认分类
                    this.activeName = this.categoryTypes[0].code + ""
                }
                // 查询左侧菜单数据
                this.findLeftTree(id);
                if (id != null && id !== '') {
                    // 展示文章
                    this.findId(id);
                    this.showType(2)
                } else {
                    // 展示列表
                    this.onLoad();
                    this.showType(1)
                }

            })
        }
        ,
        /**
         * 直接触发：  首次自动加载 / 点击分页 / 切换分页 / 跳转也 / 点击刷新
         * 被调用触发：搜索后 /  添加/编辑保存后 / 删除后
         * @author wangsong
         */
        onLoad() {
            // 列表默认查询顶级数据
            if (this.search.pid == null) {
                this.search.pid = "0";
            } else {
            }
            this.search.type = this.activeName;
            // 查询
            this.crud.list(this, false);
            this.crud.doLayout(this, this.$refs.crudMenu);
        }
        ,
        findId(id) {
            this.crud.get(this.uri.info + "/" + id).then((res) => {
                if (res.data.data.content != null && res.data.data.content != "") {
                    this.contentHtml = xss.process(VueMarkdownEditor.themeConfig.markdownParser.render(res.data.data.content));
                } else {
                    this.contentHtml = "暂无内容"
                }
            })
        }
        ,

        // 搜索,并重置页数为1
        searchChange(params, done) {
            this.page.currentPage = 1;
            this.findLeftTree();
            this.onLoad();
            done();
        }
        ,
        // 远程排序
        sortChange(column, prop, order) {
            if (column.order != null) {
                let order = column.order.replace("ending", "")
                let sort = column.prop.replace(/([A-Z])/g, "_$1").toLowerCase()
                console.log("排序字段:%s  排序规则：%s", sort, order)
                this.search.sort = sort;
                this.search.order = order;
                this.onLoad();
            }
        },

        /**
         * 查询左侧 菜单数据
         */
        findLeftTree(id) {
            this.crud.get(this.uri.infoList, {sort: this.search.sort, order: this.search.order, isTree: true, type: this.activeName}).then(res => {
                this.treeData = res.data.data;
                if (id != null && id !== '') {
                    this.$nextTick(() => {
                        this.$refs.tree.setCurrentKey(id);
                        // 等setCurrentKey生效在定位标题
                        this.$nextTick(() => {
                            // 滚动定位标题 获取要滚动到的元素 / 将页面滚动到元素的位置
                            var targetElement = document.getElementsByClassName('is-current');
                            targetElement[0].scrollIntoView({behavior: 'auto', block: 'center'});
                        })
                    });
                }
            })
        },

        // 添加/编辑保存数据后 关闭弹层+ true-刷新列表 false-不刷新
        closeDialog(isRefresh) {
            this.addDialogVisible = false;
            this.updDialogVisible = false;
            this.updPidDialogVisible = false;
            this.rowData = {};
            if (isRefresh != null && isRefresh) {
                this.onLoad();
            }
        }
        ,
        // 行编辑
        updRow(row, type) {
            this.rowData = row;
            switch (type) {
                case 0:
                    // 添加顶级
                    this.$router.push({
                        path: "/viewsdoc/docInfo/docInfoAdd?time=" + new Date().getTime(),
                        query: {
                            //id: row.id,
                            //pname: row.name,
                            type: this.activeName
                        }
                    });
                    break;
                case 1:
                    // 编辑
                    //  this.updDialogVisible = true;
                    this.$router.push({
                        path: '/viewsdoc/docInfo/docInfoUpd?time=' + new Date().getTime(),
                        query: {
                            id: row.id
                        }
                    })
                    break;
                case 2:
                    // 添加
                    this.$router.push({
                        path: "/viewsdoc/docInfo/docInfoAdd?time=" + new Date().getTime(),
                        query: {
                            pid: row.id,
                            pname: row.name,
                            type: this.activeName
                        }
                    });
                    break;
                case 3:
                    // 复制添加
                    this.$router.push({
                        path: "/viewsdoc/docInfo/docInfoAdd?time=" + new Date().getTime(),
                        query: {
                            copyId: row.id,
                            pid: row.id,
                            pname: row.name,
                            type: this.activeName
                        }
                    });
                    break;
                case 4:
                    // 变更父级
                    this.updPidDialogVisible = true;
                    break;
                case 5:
                    // 删除(左边树上删除)
                    this.$confirm('此操作将永久删除该文档及子文档, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        this.crud.del(this.uri.info + "/" + this.rowData.id).then((res) => {
                            this.findLeftTree();
                            this.onLoad();
                        })
                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '已取消删除'
                        });
                    });
                    break;
                default:
                    this.$message.error('操作类型错误');
                    break;
            }
        }
        ,
        // 行删除
        rowDel(row, index) {
            this.crud.delRow(this, this.uri.info, row.id, index);
        }
        ,
        // 启用/禁用
        updDisable(row, index, disable) {
            this.crud.put(this.uri.updDisable + "/" + row.id, null, {disable: disable});
        }
        ,
        // 编辑排序
        rowSortBlur(row) {
            if (this.rowData.sort != row.sort) {
                this.crud.put(this.uri.updSort + "/" + row.id, null, {sort: row.sort});
            }
        }
        ,

        // 点击保存行数据(供行操作的任意地方获取数据)
        handleRowClick(row) {
            this.rowData = JSON.parse(JSON.stringify(row));
        }
        ,
        // 自动配置,单元格样式数字，对指定列设置字体颜色,大小，粗细等
        cellStyle({row, column}) {
            if (column.property == "disable") {
                // fontWeight: 'bold',fontSize: '20'
                return row.disable == 0 ? {color: 'green'} : {color: 'red'}
            }
        }
        ,
        /**
         * 点击左菜单重置右菜单数据
         * @param data
         */
        nodeClick(data) {
            console.log("点击左菜单");

            let docList = document.getElementById("docList");
            let docContentHtml = document.getElementById("docContentHtml");
            if (data.showType == 1) {
                // 重置右菜单数据
                // this.$message.success(JSON.stringify(data))
                this.rowData = data;
                this.search.pid = data.id;
                this.onLoad();
                this.showType(1)
            } else {
                // 展示内容
                this.findId(data.id)
                this.showType(2)
            }
        }
        ,
        handleClick(tab, event) {
            // 当前选中分类类型
            this.activeName = tab.name;

            // 清除选中tree, 重置展示按钮
            this.rowData = {};
            this.search.pid = null;

            // 根据类型查询
            this.findLeftTree();
            // 查询拉取表格数据
            this.onLoad();
            this.showType(1)
        }
        ,
        showType(type) {
            let docList = document.getElementById("docList");
            let docContentHtml = document.getElementById("docContentHtml");
            console.log("---------")
            if (type == 1) {
                // 展示列表 1
                docList.style.display = "block";
                docContentHtml.style.display = "none"
            } else {
                // 展示内容 2
                docContentHtml.style.display = "block";
                docList.style.display = "none"
            }
        },
        /**
         * 通过 分类code 获取name
         * @param code
         * @returns {string|*}
         */
        getCategoryType(code) {
            for (const category of this.categoryTypes) {
                if (category.code == code) {
                    return category.name;
                }
            }
            return "";
        },

        // 更新html 数据
        refreshHtml(row) {
            console.log("======== 开始更新 md 格式数据为 html ==========")
            let categoryName = this.getCategoryType(this.activeName)
            this.$confirm('更新 【' + categoryName + '】 下所有文档在数据库保存的HTML数据?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                // 遍历所有文档
                this.crud.get(this.uri.listIdNames).then((async res => {
                    let docs = res.data.data;
                    for (let i = 0; i < docs.length; i++) {
                        // 查询每一篇文档
                        this.crud.get(this.uri.info + "/" + docs[i].id).then((res => {
                            // 更新每一篇文档的html
                            let doc = res.data.data;
                            if (doc.content != null && doc.content != "") {
                                doc.contentHtml = xss.process(VueMarkdownEditor.themeConfig.markdownParser.render(doc.content));
                                this.crud.put(this.uri.updHtml + "/" + doc.id, {contentHtml: doc.contentHtml});
                            }
                        }));
                        // 暂停500毫秒
                        await this.delay(500)
                    }
                }));
            }).catch(() => {
                this.$message({type: 'info', message: '已取消更新'});
            });
        },
        delay(time) {
            return new Promise(function (resolve) {
                setTimeout(resolve, time);
            });
        }
        ,
        siteMap() {
            console.log("生成站点地图")
            // let categoryName = this.getCategoryType(this.activeName)
            this.$confirm('生成当前租户的站点地图?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.crud.download(this.uri.generateSiteMap, null, null);
            }).catch(() => {
                this.$message({type: 'info', message: '已取消导出'});
            });
        }
        ,
        /**
         * 删除指定类型下的文档
         */
        delDocAllByType() {
            console.log("删除指定分类文档")
            let categoryName = this.getCategoryType(this.activeName)
            this.$confirm('删除 【' + categoryName + '】 下的所有文档? ', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.crud.del(this.uri.delByType, null, {type: this.activeName});
            }).catch(() => {
                this.$message({type: 'info', message: '已取消'});
            });
        }
        ,
        /**
         * 导出 Md
         * @author wangsong
         * @email  1720696548@qq.com
         * @date  2022/12/23 0023 13:15
         * @version 1.0.0
         */
        exportMd() {
            console.log("导出 Md")
            let categoryName = this.getCategoryType(this.activeName)
            this.$confirm('导出 【' + categoryName + '】 下的所有文档? 导出将异步执行, 完成后会发送通知, 注意查看消息, 完成可点击【导出下载】按钮获取文件', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                if (this.treeData == null || this.treeData.length == 0) {
                    this.$message.error(categoryName + ' 下没有文档');
                    // throw new Error("当前目录下没有文档");
                } else {
                    this.crud.post(this.uri.exportMd, null, {type: parseInt(this.activeName)});
                }

            }).catch(() => {
                this.$message({type: 'info', message: '已取消导出'});
            });
        }
        ,
        /**
         * 导出 Md exportMdDownload 后的选择
         * @author wangsong
         * @email  1720696548@qq.com
         * @date  2022/12/23 0023 13:15
         * @version 1.0.0
         */
        exportMdDownload() {
            console.log("导出 Md")
            let categoryName = this.getCategoryType(this.activeName)
            this.$confirm('导出 【' + categoryName + '】 下的所有文档? 需先进行【导出文档】操作,在点击【导出下载】', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                if (this.treeData == null || this.treeData.length == 0) {
                    this.$message.error(categoryName + ' 下没有文档');
                    // throw new Error("当前目录下没有文档");
                } else {
                    this.crud.get(this.uri.getExportMdDownloadPath, {type: this.activeName}, null).then((res) => {
                        window.location.href = proxyPath + "/" + res.data.data
                    })
                }

            }).catch(() => {
                this.$message({type: 'info', message: '已取消导出下载'});
            });
        },
        /**
         * 静态化文档
         */
        staticMd() {
            console.log("静态化文档")
            // let categoryName = this.getCategoryType(this.activeName)
            this.$confirm('生成当前租户的的静态化HTML', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.crud.download(this.uri.staticMd, null, null);
            }).catch(() => {
                this.$message({type: 'info', message: '已取消静态化'});
            });
        },
        /**
         * 静态化文档下载
         */
        staticMdDownload() {
            console.log("下载 静态化后的 HTML")
            let categoryName = this.getCategoryType(this.activeName)
            this.$confirm('下载静态化后的 HTML? 需先进行【静态化文档】操作,在点击【静态化下载】', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                window.location.href = proxyPath + "/File/dist.zip"
            }).catch(() => {
                this.$message({type: 'info', message: '已取消导出下载'});
            });
        }
    }
}
</script>